﻿/* 
#include <process.h>
#include <Windows.h>
#include <iostream>

int tickets = 10;
HANDLE iMutex = (HANDLE)0xff;

void sellTickets(void* ptr)
{
    while (tickets > 0)
    {
        WaitForSingleObject(iMutex, INFINITE);
        Sleep(10);
        std::cout << "Thread 1 sell : " << tickets << std::endl;
        tickets--;
        ReleaseMutex(iMutex);
    }
}

void sellTickets2(void* ptr)
{
    WaitForSingleObject(iMutex, INFINITE);
    while (tickets > 0)
    {
        Sleep(10);
        std::cout << "Thread 2 sell : " << tickets << std::endl;
        tickets--;
    }
    ReleaseMutex(iMutex);
}

int main()
{
    HANDLE t1 = (HANDLE)_beginthread(&sellTickets, 0, nullptr);
    HANDLE t2 = (HANDLE)_beginthread(&sellTickets2, 0, nullptr);
    iMutex = (HANDLE)CreateMutex(0, FALSE, 0);

    Sleep(3500);
    //WaitForSingleObject(t1, INFINITE);  // 当线程执行完毕（退出）时，线程对象会进入已通知状态
    //WaitForSingleObject(t2, INFINITE);

    return 0;
}
*/

/*
#include <OpenThreads/Thread>
#include <OpenThreads/Mutex>
#include <OpenThreads/ScopedLock>
#include <OpenThreads/Barrier>
#include <Windows.h>
#include <iostream>

OpenThreads::Mutex mutex;
OpenThreads::Barrier bar;

class ThreadSelf : public OpenThreads::Thread
{
public:
    ThreadSelf(int a) { threadid = a; }
    virtual ~ThreadSelf()
    {
        while (isRunning())
        {
            OpenThreads::Thread::YieldCurrentThread();  // 主动让出 CPU 时间片，给 ThreadSelf 线程更多机会执行到结束。
            // join(); // 也可以阻塞等待
        }
    }

    void run()
    {

        int count = 10;
        while (--count)
        {
            OpenThreads::ScopedLock<OpenThreads::Mutex> lock(mutex); // 退出作用域时释放mutex
            Sleep(10);
            std::cout << "Thread print :" << threadid << std::endl;
        }
        bar.block(3);
    }

    int threadid;
};

int main()
{
    ThreadSelf t1(10);
    ThreadSelf t2(6);

    t1.start();
    t2.start();

    bar.block(3);
    std::cout << "Here" << std::endl;

    Sleep(3000);
    return 1;
}
*/

#include <iostream>
#include <process.h>
#include <windows.h>
#include <OpenThreads/Condition>

int condition = 0;

OpenThreads::Condition cond;
OpenThreads::Mutex mutex;

void setCondition(void* ptr)
{
    condition = 1;
    cond.signal();
}

void ifCondition(void* ptr)
{
    cond.wait(&mutex, INFINITE);
    if (condition)
    {
        std::cout << "Condition is find" << std::endl;
    }
}

int main()
{
    HANDLE t1 = (HANDLE)_beginthread(&ifCondition, 0, 0);
    Sleep(100);
    HANDLE t2 = (HANDLE)_beginthread(&setCondition, 0, 0);

    Sleep(1000);
    std::cout << "End" << std::endl;

    return 0;

}